import datetime
from helpers import Visualization
from helpers import updateInfo
from helpers.Fetching import headlineForStock
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ Account Home Page class """

    def get(self):
        user=users.get_current_user()
        
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
        
        
        # Build Total Amount Graph
        graph_text=Visualization.buildUserGraph(user)
        
        # User rank 
        q_2 = db.GqlQuery("SELECT * FROM TrendUsers WHERE totalamount>:1",current_user.totalamount)
        rank1 = q_2.count()+1
        q_3 = db.GqlQuery("SELECT * FROM TrendUsers")
        totalusers1 = q_3.count()
        
        
        #Display the competition
        displayCom=0
        q_0 = db.GqlQuery("SELECT * FROM Competition WHERE type=1 AND startdate > :1 LIMIT 1",datetime.date.today()) 
        currCompetition=q_0.fetch(1) 
        CompDate=CompName=CompNameLink=hourToStart=minToStart=secToStart=""
        if len(currCompetition)!=0:
            currCompetition=currCompetition[0]
            #computing time elapsed to the competition start time
            hourToStart, minToStart, secToStart= updateInfo.computeTimeElapse(currCompetition.startdate)
            CompNameLink+="/Competition?id=%s&PKey=%s" % (currCompetition.key(),currCompetition.password)
            CompName=currCompetition.title
            displayCom=1
            
        newsfeeds=updateInfo.publishNewsFeeds(user,0)
               
        # Load 5 stocks list of user from database
        q_1 = db.GqlQuery("SELECT * FROM Stocks " +
        "WHERE buyer = :1 ORDER BY userPrecentChange DESC,stockref LIMIT 0,3", user)
        
        # Get popular stocks headlines
        headlines=""
        prevStock=""
        headFlag=0
        for p in q_1:
            if p.stockref<>None:
                if prevStock==p.stockref.stockname:
                    continue
                prevStock=p.stockref.stockname
                HeadlineTitle, HeadlineURL = headlineForStock(prevStock)
                if HeadlineTitle==-1:
                    continue
                printPercentage, fontColor, changeSign= updateInfo.getPerInfo(p.userPrecentChange)
                try:
                    headlines+="<div>(%s&nbsp;<font color=\"%s\">%s%.2f</font>)&nbsp;&nbsp;<a href=\"%s\" target=\"_blank\">%s</a></div>" % (p.stockref.stockname,fontColor, changeSign,printPercentage, HeadlineURL, HeadlineTitle)
                    headFlag=1
                except :
                    # Wrong charcters downloaded
                    continue
                
        if headFlag==0:
            headlines+="<div>No headlines available yet</div>"
        bool=1
            
        template_values = {
            'graph_text': graph_text,
            'current_user_totalamount': current_user.totalamount,
            'current_user_bankamount': current_user.bankamount,
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'headlines': headlines,
            'CompDate': CompDate,
            'rank1':rank1,
            'bool':bool,
            'totalusers1':totalusers1,
            'CompNameLink': CompNameLink,
            'CompName' : CompName,
            'hourToStart':hourToStart,
            'minToStart':minToStart,
            'secToStart':secToStart,
            'displayCom':displayCom,
            'newsfeeds': newsfeeds,
            'logintext' : 'Sign Out',
            'categoryName' : '',
            'setHead' : 1,
            'headContent' : 'account_head.html',
            'maincontent' : 'account_main.html',
            'account_main_content' : 'account_main_con.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [('/account', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)


if __name__ == "__main__":
    main()
